package com.example.administrator.u17.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.administrator.u17.R;
import com.example.administrator.u17.activity.ZhangJieActivity;
import com.example.administrator.u17.adapter.DingYueAdapter;
import com.example.administrator.u17.config.NetConfig;
import com.example.administrator.u17.modle.DingYueBean;
import com.example.administrator.u17.modle.MyDbBean;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Administrator on 2016/11/14.
 */

public class DingYueFragmnet extends Fragment{
    private ArrayList<DingYueBean.Comics> mData;
    private DingYueAdapter mAdapter;
    private PullToRefreshListView mListView;
    private int mCurrentPage=1;
    private DbManager mDbManager;
    private String mPath;
    private ConnectivityManager mConnectivityManager;//获取网络通讯类的实例  以便判断是否有网

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=View.inflate(getActivity(), R.layout.dingyue_fragment,null);
        mDbManager=x.getDb(new DbManager.DaoConfig());
        //实例化
        mConnectivityManager= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        initView(view);

        try {
            initData();
        } catch (DbException e) {
            e.printStackTrace();
        }

        setData();
        setListener();
        return view;
    }

    private void setListener() {
        mListView.setMode(PullToRefreshBase.Mode.BOTH);
        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
               mCurrentPage=1;
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                mCurrentPage++;
                loadData();
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //PullToRefreshListView的点击事件
                mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Intent intent=new Intent(getActivity(),ZhangJieActivity.class);
                        intent.putExtra("id",mData.get(position).comicId);
                        startActivity(intent);
                    }
                });
            }
        });



    }

    private void setData() {
        mListView.setAdapter(mAdapter);
    }

    private void initData() throws DbException {
        mData = new ArrayList<>();
        mAdapter = new DingYueAdapter(getActivity(), mData);
        loadData();
//        //判断网络是否可用
//        boolean usable=mConnectivityManager.getActiveNetworkInfo().isAvailable();
//
//        //网络不可用并且数据库不为空，加载数据库中数据
//        if (!usable&&mDbManager!=null){
//            mData.clear();
//            try {
//                List<MyDbBean> data=mDbManager.selector(MyDbBean.class).where("path","=",mPath).findAll();
//                DingYueBean bean=new Gson().fromJson(data.get(0).json,DingYueBean.class);
//                mData.addAll(bean.data.returnData.comics);
//                mAdapter.notifyDataSetChanged();
//                mListView.onRefreshComplete();
//            } catch (DbException e) {
//                e.printStackTrace();
//            } catch (JsonSyntaxException e) {
//                e.printStackTrace();
//            }
//        }else if (usable){//否则，加载网络数据
//            mData.clear();
//            loadData();
//        }else {
//            Toast.makeText(getActivity(), "网络异常", Toast.LENGTH_SHORT).show();
//        }


    }
    private void loadData(){
        mPath = NetConfig.DingYue_Path+mCurrentPage;
        RequestParams params=new RequestParams(mPath);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //数据库存储
                MyDbBean myDb=new MyDbBean();
                myDb.json=result;
                myDb.path=mPath;
                Calendar calendar=Calendar.getInstance();
                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
                myDb.time=format.format(calendar.getTime());
                try {
                    mDbManager.save(myDb);
                } catch (DbException e) {
                    e.printStackTrace();
                }

                DingYueBean bean=new Gson().fromJson(result,DingYueBean.class);
                mData.addAll(bean.data.returnData.comics);
                mAdapter.notifyDataSetChanged();
                mListView.onRefreshComplete();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mData.clear();
                try {
                    List<MyDbBean> data=mDbManager.selector(MyDbBean.class).where("path","=",mPath).findAll();
                    DingYueBean bean=new Gson().fromJson(data.get(0).json,DingYueBean.class);
                    mData.addAll(bean.data.returnData.comics);
                    mAdapter.notifyDataSetChanged();
                    mListView.onRefreshComplete();
                } catch (DbException e) {
                    e.printStackTrace();
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mListView.onRefreshComplete();
            }
        });

    }

    private void initView(View view) {
        mListView= (PullToRefreshListView) view.findViewById(R.id.pl_dingyue_fragment);
    }
}
